/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.playground.client.websockets.application;

import com.google.gson.Gson;
import com.playground.client.websockets.entity.message.response.LoginResponseMessage;
import com.playground.core.entity.LoggedPlayer;
import com.playground.core.service.LoginService;
import com.sun.grizzly.tcp.Request;
import com.sun.grizzly.websockets.WebSocket;
import com.sun.grizzly.websockets.WebSocketApplication;

/**
 *
 * @author Tiago Peres
 */
public class LoginApplication extends WebSocketApplication{
    private LoginService loginService;
    
    public LoginApplication(LoginService ls){
        loginService = ls;
    }

    @Override
    public boolean isApplicationRequest(Request rqst) {
        System.out.println(loginService == null ? "!!! ls is null" : "+++ ls is not null");
        return rqst.requestURI().toString().endsWith("/login");
        //return true;
    }
    
    @Override
    public void onMessage(WebSocket socket, String data) {
        System.out.println("Message received");
        long id = Long.parseLong(data);
        System.out.println(id);
        LoggedPlayer lp = loginService.login(id);
        LoginResponseMessage msg = new LoginResponseMessage();
        if (null != lp){
            System.out.println("not null");
            msg.setPlayerId(id);
            msg.setPlayerKey(lp.getKey());
            msg.setSuccess(true);
            String json = new Gson().toJson(msg);
            System.out.println(json);
            socket.send(json);
        } else{
            System.out.println("null");
            msg.setSuccess(false);
            socket.send(new Gson().toJson(msg));
        }
        //socket.send("{\"success\": false;}");
    }
}
